package com.ikangtai.shecare.common;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.preference.PreferenceManager;

import com.bugtags.library.Bugtags;
import com.bumptech.glide.request.target.ViewTarget;
import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.al.DayUnitDSOutput;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.PushUtil;
import com.squareup.okhttp.OkHttpClient;
import com.umeng.socialize.PlatformConfig;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class
App extends Application {
    public static int appKilledFlag = -1;

    public static Context context;
    private static OkHttpClient mOKHttpClient;
    public static String userName;
    public static String userPswd;
    public static final String USER_INFO_SHARED_PREFERENCE = "userInfo";

    public static String authToken = null;
    public static final int HTTP_RESP_OK = 200;
    public static final int HTTP_RESP_FAIL = 500;
    public static final int HTTP_RESP_TOKEN_TIME_OUT = 201;
    public static final int VERIFICATION_CODE_WRONG = 208;
    public static final int VERIFICATION_CODE_OVERDUE = 208;
    public static final int UNREGISTERED = 202;
    public static final int FORMAT_WRONG = 214;
    public static final int LAST_CONNECT_TIME = 18;

    public static final int HTTP_CONNECT_TIMEOUT = 10;
    public static final int HTTP_READ_WRITE_TIMEOUT = 60;

    //sharedPreference.xml相关
    public static final String SHARED_PREF_USER_NAME = "userName";
    public static final String SHARED_PREF_USER_TOKEN = "authToken";

    //把sqlite里有关用户preference的值读到memory中
    public static String memory_preference_nickName;
    public static int memory_preference_userState;
    public static String memory_preference_birthday;
    public static int memory_preference_periodLen = 0;
    public static int memory_preference_mensesLen = 0;
    public static int memory_preference_mensesType = 2;
    public static String memory_preference_lastPeriodDate = "";
    public static String memory_preference_taskIDs;
    public static String memory_preference_isDataDownloaded;
    public static String memory_preference_macAddress;
    public static String memory_preference_lastConnectTime;
    public static int hardwareRevision = 2;

    public static boolean ALERT_REPEAT_SUN = false;
    public static boolean ALERT_REPEAT_MON = true;
    public static boolean ALERT_REPEAT_TUE = true;
    public static boolean ALERT_REPEAT_WED = true;
    public static boolean ALERT_REPEAT_THU = true;
    public static boolean ALERT_REPEAT_FRI = true;
    public static boolean ALERT_REPEAT_STA = false;

    //备孕，避孕状态
    public static int STATUS_BIYUN = 1;
    public static int STATUS_BEIYUN = 0;
    public static int status = STATUS_BEIYUN;

    public static boolean isBindActivityActive = false;
    public static boolean isMyDeviceActivityActive = false;

    //首页大圆圈算法相关数据
    public static List<DayUnitDSOutput> dayUnitDSOutputsList = new ArrayList<>();
    public static Map<Long, DayUnitDSOutput> DayUnitDSOutputMap = new HashMap<>();

    public static List<Activity> activityList = new ArrayList<>();

    private static boolean authTokenIsRefreshed = false;

    // baseUrlPath：后台json交互接口地址
    // 正式服务器: "http://www.ikangtai.com/ThermometerV2/"
    // 测试服务器: "http://test.ikangtai.com/V2/"
    public static String baseUrlPath;
    // articleImageBaseUrlPath：文章图片存放地址
    // 正式服务器： "http://www.ikangtai.com/shecareUser/bbs/small/"
    // 测试服务器： "http://www.ikangtai.com/shecareUserTest/bbs/small/"
    public static String articleImageBaseUrlPath;
    // knowledge fragment 首页地址
    // 正式服务器： "http://ikangtai.com/knowledgeService/knowledge.html?userHardwareVersion=" + hardwareVersion
    // 测试服务器： "http://test.ikangtai.com/knowledgeService/knowledge.html?userHardwareVersion=" + hardwareVersion
    public static int hardwareVersion = 2;
    public static String fragmentKnowledgeUrlPath;
    // knowledge 文章列表地址 0~3 分别表示备孕，避孕，孕期，产后文章列表
    // 正式服务器： "http://ikangtai.com/knowledgeService/knowledge_list.html?id="
    // 测试服务器： "http://test.ikangtai.com/knowledgeService/knowledge_list.html?id="
    public static String knowledgeArticleListUrlPath;
    // knowledge 具体某篇文章内容
    // 正式服务器： "http://ikangtai.com/knowledgeService/knowledge_content.html?id="
    // 测试服务器： "http://test.ikangtai.com/knowledgeService/knowledge_content.html?id="
    public static String knowledgeArticleUrlPath;
    // 正式服务器： "http://www.ikangtai.com/shecareUser/user/head/"
    // 测试服务器： "http://www.ikangtai.com/shecareUserTest/user/head/"
    public static String avatarUrlPath;
    // 正式服务器： "http://www.ikangtai.com/shecareUser/gran/"
    // 测试服务器： "http://www.ikangtai.com/shecareUserTest/gran/"
    public static String gynaeUrlPath;//试纸图片地址

    //文章收藏列表
    public static final int DB_NOT_SYNCED = 0; //sqlite 数据与网络侧没有同步
    public static final int DB_SYNCED = 1; //sqlite 数据与网络侧同步

    public static List<CollectedArticle> collectedArticleList = new ArrayList<>();
    public static List<String> collectedArticleIdList = new ArrayList<>();
    public static HashMap<String, String> articleId2CollectionIDMap = new HashMap<>();

    public static boolean isArticleCollected(String collectedArticleId) {
        return collectedArticleIdList.contains(collectedArticleId);
    }

    @Override
    public void onCreate() {
        super.onCreate();

        ViewTarget.setTagId(R.id.glide_id);
        String buildType = getResources().getString(R.string.buildType);
        if (buildType.equals("test")) {
            baseUrlPath = "http://test.ikangtai.com/V2/";
            articleImageBaseUrlPath = "http://www.ikangtai.com/shecareUserTest/bbs/small/";
            fragmentKnowledgeUrlPath = "http://test.ikangtai.com/knowledgeService/knowledge.html?userHardwareVersion=" + getBoundHwVersion();
            knowledgeArticleListUrlPath = "http://test.ikangtai.com/knowledgeService/knowledge_list.html?id=";
            knowledgeArticleUrlPath = "http://test.ikangtai.com/knowledgeService/knowledge_content.html?id=";
            avatarUrlPath = "http://www.ikangtai.com/shecareUserTest/user/head/";
            gynaeUrlPath = "http://www.ikangtai.com/shecareUserTest/gran/";
        } else {
            baseUrlPath = "http://www.ikangtai.com/ThermometerV2/";
            articleImageBaseUrlPath = "http://www.ikangtai.com/shecareUser/bbs/small/";
            fragmentKnowledgeUrlPath = "http://ikangtai.com/knowledgeService/knowledge.html?userHardwareVersion=" + getBoundHwVersion();
            knowledgeArticleListUrlPath = "http://ikangtai.com/knowledgeService/knowledge_list.html?id=";
            knowledgeArticleUrlPath = "http://ikangtai.com/knowledgeService/knowledge_content.html?id=";
            avatarUrlPath = "http://www.ikangtai.com/shecareUser/user/head/";
            gynaeUrlPath = "http://www.ikangtai.com/shecareUser/gran/";
        }
        PushUtil.initialize(getApplicationContext());


        context = getApplicationContext();//返回应用的上下文
        Bugtags.start("a2f20ac1ba6633024d45ae822b13ca51", this, Bugtags.BTGInvocationEventNone);

        PlatformConfig.setWeixin("wx168db3f946974da1", "e4e1c2b373a0bfb4dc31e330896e5fa8"); //微信 appid appsecret
        PlatformConfig.setSinaWeibo("3700640690", "3acc65ce26128e33bda73284444cabed"); //新浪微博 appkey appsecret
        PlatformConfig.setQQZone("1105477535", "RYIgLqUmXymPDWNp");// QQ和Qzone appid appkey
    }

    private int getBoundHwVersion() {
        return hardwareVersion;
    }

    public static void clearAllActivities() {
        for (int i = activityList.size() - 1; i >= 0; i--) {

            if (!activityList.get(i).isFinishing()) {
                activityList.get(i).finish();
            }
        }

        activityList.clear();
    }

    /**
     * 数据存储
     * 用户信息存储
     *
     * @param key
     * @param value
     */
    public static void saveUserPreference(String key, String value) {
        context.getSharedPreferences(USER_INFO_SHARED_PREFERENCE, Activity.MODE_PRIVATE).edit()
                .putString(key, value).commit();
    }

    public static void saveUserPreference(String key, boolean value) {
        context.getSharedPreferences(USER_INFO_SHARED_PREFERENCE, Activity.MODE_PRIVATE).edit()
                .putBoolean(key, value).commit();
    }

    public static void saveUserPreference(String key, int value) {
        context.getSharedPreferences(USER_INFO_SHARED_PREFERENCE, Activity.MODE_PRIVATE).edit()
                .putInt(key, value).commit();
    }

    public static void saveUserPreference(String key, long value) {
        context.getSharedPreferences(USER_INFO_SHARED_PREFERENCE, Activity.MODE_PRIVATE).edit()
                .putLong(key, value).commit();
    }

    public static void saveUserPreference(String key, float value) {
        context.getSharedPreferences(USER_INFO_SHARED_PREFERENCE, Activity.MODE_PRIVATE).edit()
                .putFloat(key, value).commit();
    }

    public static String getStringUserPreference(String key) {
        return context.getSharedPreferences(USER_INFO_SHARED_PREFERENCE, Activity.MODE_PRIVATE).
                getString(key, null);
    }

    public static String getStringUserPreference(String key, String value) {
        return context.getSharedPreferences(USER_INFO_SHARED_PREFERENCE, Activity.MODE_PRIVATE).
                getString(key, null);
    }

    public static int getIntUserPreference(String key) {
        return context.getSharedPreferences(USER_INFO_SHARED_PREFERENCE, Activity.MODE_PRIVATE).
                getInt(key, 0);
    }

    public static long getLongUserPreference(String key) {
        return context.getSharedPreferences(USER_INFO_SHARED_PREFERENCE, Activity.MODE_PRIVATE).
                getLong(key, 0l);
    }

    public static float getFloatUserPreference(String key) {
        return context.getSharedPreferences(USER_INFO_SHARED_PREFERENCE, Activity.MODE_PRIVATE).
                getFloat(key, 0f);
    }

    public static boolean getBooleanUserPreference(String key) {
        return context.getSharedPreferences(USER_INFO_SHARED_PREFERENCE, Activity.MODE_PRIVATE).
                getBoolean(key, true);
    }


    /**
     * 数据存储
     * 设备等用户无关信息存储
     *
     * @param key
     * @param value
     */
    public static void savePreference(String key, String value) {
        PreferenceManager.getDefaultSharedPreferences(context).edit()
                .putString(key, value).commit();
    }

    public static void savePreference(String key, int value) {
        PreferenceManager.getDefaultSharedPreferences(context).edit()
                .putInt(key, value).commit();
    }

    public static void savePreference(String key, long value) {
        PreferenceManager.getDefaultSharedPreferences(context).edit()
                .putLong(key, value).commit();
    }

    public static void savePreference(String key, Boolean value) {
        PreferenceManager.getDefaultSharedPreferences(context).edit()
                .putBoolean(key, value).commit();
    }

    public static boolean getPreferenceBoolean(String key) {
        return PreferenceManager.getDefaultSharedPreferences(context)
                .getBoolean(key, false);
    }

    public static String getPreference(String key) {
        return PreferenceManager.getDefaultSharedPreferences(context)
                .getString(key, "");
    }

    public static int getPreferenceInt(String key) {
        return PreferenceManager.getDefaultSharedPreferences(context).getInt(
                key, 0);
    }

    public static int getPreferenceInt(String key, int def) {
        return PreferenceManager.getDefaultSharedPreferences(context).getInt(
                key, def);
    }

    public static long getPreferenceLong(String key, long def) {
        return PreferenceManager.getDefaultSharedPreferences(context).getLong(
                key, def);
    }

    public static boolean getPreferenceBoolean(String key, boolean def) {
        return PreferenceManager.getDefaultSharedPreferences(context)
                .getBoolean(key, def);
    }

    // mOKHttpClient单例
    public static OkHttpClient getOKHttpClient() {

        if (mOKHttpClient == null) {
            synchronized (OkHttpClient.class) {
                if (mOKHttpClient == null)
                    mOKHttpClient = new OkHttpClient();
            }
        }

        return mOKHttpClient;
    }

    public static String getStatus(int status) {
        AppLog.i("status=" + status);
        return status == 0 ? context.getString(R.string.preganecy) : context.getString(R.string.contraception);
    }



}
